import { View, Text, Image } from '@tarojs/components';
import { Component } from 'react';
import Tabs from '@/components/Tabs';
import Taro from '@tarojs/taro';
import dayjs from 'dayjs';
import { globalStore } from '@/store';
import Radio from '@/components/Radio';
import InputItem from '@/components/InputItem';
import { createOrder } from '@/service/apis/order/index';
import { getAddressList } from '@/service/apis/mine/index';
import { getServiceDetail } from '@/service/apis/service';
import { AtTag, AtList, AtListItem, AtIcon, AtButton } from 'taro-ui';
import { getAppointmentDate, getFirstDay } from '@/utils/utils';
import ProductItem from '../component/ProductItem';
import SelectUser from '../component/SelectUser';
import SelectAddress from '../component/SelectAddress';
import TimeModal from '../component/TimeModal/index';
import './index.scss';

function getAppointDate() {
  const currentDay = getFirstDay();
  const time = getAppointmentDate();
  console.log('time: ', time);
  return {
    name: `${dayjs(currentDay).format('YYYY-MM-DD')} ${time.title} ${time.name}`,
    value: `${dayjs(currentDay).format('YYYY-MM-DD')} ${time.value}`,
  };
}

/**
 * 提交订单
 * @returns
 */
export default class Index extends Component {
  state = {
    current: 0,
    serviceType: '1',
    visibleSelect: false,
    visibleAddress: false,
    tabList: [],
    appointDateMoalShow: false,
    count: 1,
    skuInfo: {
      price: 0,
    },
    productInfo: {},
    userList: [],
    currentUser: {
      name: '请选择提货人',
    },
    currentPayType: '2',
    submitForm: {
      time: getAppointDate().name,
      pickup_time: getAppointDate().value,
      remark: '',
    },
  };

  componentDidMount = async () => {
    const querys: any = Taro.getCurrentInstance().router?.params;
    if (querys?.id && querys?.skuId) {
      this.getServiceDetail(querys.id, querys?.skuId);
    }
    if (querys?.count) {
      this.setState({
        count: querys?.count,
      });
    }
  };

  componentDidShow() {
    this.getAddressList();
  }

  getAddressList = async () => {
    try {
      const { user_address } = await getAddressList();
      this.setState({
        userList: user_address,
      });
      if (this.state.current === 0 && user_address.length > 0) {
        let defaultUser = user_address.filter((item) => item.is_default === 1);
        if (defaultUser.length > 0) {
          this.setState({
            currentUser: defaultUser[0],
          });
        } else {
          this.setState({
            currentUser: user_address[0],
          });
        }
      }
    } catch (err) {
      Taro.showToast({
        title: err?.message,
        icon: 'none',
      });
    }
  };

  getServiceDetail = async (id: string, skuId: string) => {
    try {
      const { data } = await getServiceDetail({
        id,
      });
      if (data.detail) {
        const detail = data.detail;
        const currentSku = detail.product.filter((item) => String(item.id) === skuId)?.[0];
        this.setState({
          productInfo: detail,
          skuInfo: {
            id: skuId,
            name: currentSku?.specifications,
            price: currentSku?.vip_price,
            skuText: currentSku?.specifications
          },
        });
        if (detail.cartoon_goods_way.length === 2) {
          this.setState({
            tabList: [
              {
                title: '商家配送',
                value: 0,
              },
              {
                title: '到店自提',
                value: 1,
              },
            ],
          });
          return;
        }
        if (detail.cartoon_goods_way[0] === '到店自提') {
          this.setState({
            tabList: [
              {
                title: '到店自提',
                value: 1,
              },
            ],
            current: 0,
            serviceType: '2',
          });
        } else {
          this.setState({
            tabList: [
              {
                title: '商家配送',
                value: 1,
              },
            ],
            current: 0,
            serviceType: '1',
          });
        }
      } else {
        Taro.showToast({
          title: '商品详情数据错误',
          icon: 'none',
        });
      }
    } catch (err) {
      console.log('err: ', err);
      Taro.showToast({
        title: err?.message,
        icon: 'none',
      });
    }
  };

  onTabChange = (value: number) => {
    this.setState({
      current: value,
      serviceType: value === 0 ? '1' : '2',
    });
  };

  onSubmit = () => {
    const { currentUser } = this.state;
    if (!currentUser.id) {
      return Taro.showToast({
        title: '请选择提货人',
        icon: 'none',
      });
    }
    this.createOrder();
  };

  onSelectUser = (user: any) => {
    console.log('user: ', user);
    this.setState({
      currentUser: user,
      visibleSelect: false,
      visibleAddress: false,
    });
  };

  openSelect = () => {
    console.log('2323');
    this.setState({
      visibleSelect: true,
    });
  };

  onAppointTimeChange = (time: any) => {
    console.log('time: ', time);
    this.setState({
      submitForm: {
        ...this.state.submitForm,
        time: time.name,
        pickup_time: time.value,
      },
      appointDateMoalShow: false,
    });
  };

  setAppointDateModalShow = () => {
    this.setState({
      appointDateMoalShow: true,
    });
  };

  // 创建订单
  createOrder = async () => {
    const querys: any = Taro.getCurrentInstance().router?.params;
    const { submitForm, currentUser, current, currentPayType, skuInfo, serviceType } = this.state;
    const params = {
      ...submitForm,
      remark: submitForm.remark || '无',
      id: querys?.id,
      skuId: querys?.skuId,
      address_id: currentUser.id,
      payType: currentPayType,
      serviceType: serviceType,
      ziti: serviceType === '2' ? '1' : '0',
      number: querys.count || 1,
    };
    try {
      const { data } = await createOrder(params);
      const orderCode = data.order_sn;
      const price = skuInfo.price * (querys.count || 1);
      if (data.pay_config) {
        const { nonceStr, package: packageStr, paySign, signType, timeStamp } = data.pay_config;
        Taro.requestPayment({
          timeStamp,
          nonceStr,
          package: packageStr,
          signType,
          paySign,
          success: (res) => {
            console.log('res: ', res);
            if (res) {
              Taro.redirectTo({
                url: `/subPages/order/result/index?res=1&orderCode=${orderCode}&price=${price}`,
              });
            }
          },
          fail: (err) => {
            console.log('err: ', err);
            if (err?.errMsg.indexOf('cancel')) {
              // 用户主动取消支付
              Taro.redirectTo({
                url: `/subPages/order/result/index?res=0&orderCode=${orderCode}&price=${price}`,
              });
            } else {
              Taro.redirectTo({
                url: `/subPages/order/result/index?res=2&orderCode=${orderCode}&price=${price}`,
              });
            }
          },
        });
      } else {
        if (orderCode) {
          Taro.redirectTo({
            url: `/subPages/order/result/index?res=1&orderCode=${orderCode}&notPay=1&price=${price}`,
          });
        }
      }
      console.log('data: ', data);
    } catch (err) {
      Taro.showToast({
        title: err?.message || '创建订单失败，请稍候重试',
        icon: 'none',
      });
    }
  };

  onRemarkChange = (value: string) => {
    this.setState({
      submitForm: {
        ...this.state.submitForm,
        remark: value,
      },
    });
  };

  onOpenAddModal = () => {
    this.setState({
      visibleAddress: true,
    });
  };

  onPayTypeChange = (value: string) => {
    console.log('value: ', value);
    this.setState({
      currentPayType: value,
    });
  };

  openMap = () => {
    const { lat, lng } = globalStore.currentShop;
    Taro.openLocation({
      latitude: lat,
      longitude: lng,
      success: () => {},
    });
  };

  render() {
    const {
      current,
      serviceType,
      tabList,
      appointDateMoalShow,
      productInfo,
      skuInfo,
      currentUser,
      visibleSelect,
      visibleAddress,
      userList,
      submitForm,
      currentPayType,
      count,
    } = this.state;
    console.log('current', current);
    return (
      <View className="submit-order-content">
        <Tabs current={current} tabList={tabList} onChange={this.onTabChange}>
          <View className="order-content">
            {serviceType === '1' ? (
              <View className="address-info" onClick={this.onOpenAddModal}>
                {currentUser.id ? (
                  <View>
                    <View className="city-text">
                      {currentUser.province_id + currentUser.city_id + currentUser.area_id}
                    </View>
                    <View className="addess-text">
                      {currentUser.address}
                      <AtIcon value="chevron-right" size={20} color="#CCCCCC" />
                    </View>
                    <View className="user-text">
                      收货人：{currentUser.name} {currentUser.mobile}
                    </View>
                  </View>
                ) : (
                  <View className="addess-text">
                    选择地址
                    <AtIcon value="chevron-right" size={20} color="#CCCCCC" />
                  </View>
                )}
              </View>
            ) : (
              <View>
                <View className="shop-info" onClick={this.openMap}>
                  <View className="shop-name">
                    <AtTag type="primary" size="small">
                      服务门店
                    </AtTag>
                    <Text>{productInfo.cartoon_store_store_name}</Text>
                  </View>
                  <View className="shop-address">{productInfo.cartoon_store_store_address}</View>
                  <View className="iconfont icon-weizhi" />
                </View>
                <View className="section-block">
                  <AtList>
                    <AtListItem
                      title="提货人"
                      extraText={currentUser.name}
                      onClick={this.openSelect}
                      arrow="right"
                    />
                    <AtListItem
                      onClick={this.setAppointDateModalShow}
                      title="提货时间"
                      extraText={submitForm.time}
                      arrow="right"
                    />
                  </AtList>
                </View>
              </View>
            )}

            <View className="section-block">
              <View className="shop-logo">
                <Image src={productInfo.cartoon_store_store_logo} />
                <Text>{productInfo.cartoon_store_store_name}</Text>
                {/* <AtIcon value="chevron-right" size={20} color="#CCCCCC" /> */}
              </View>
              <ProductItem count={count} product={productInfo} skuInfo={skuInfo} />
            </View>
            <View className="section-block">
              <AtList>
                <AtListItem title="商品金额" extraText={skuInfo.price} />
                <AtListItem title="合计" extraText={(skuInfo.price * count).toFixed(2)} />
              </AtList>
            </View>
            <View className="section-block service-ways">
              <View className="section-item">
                <View>支付方式</View>
                <View className="service-options">
                  <Radio
                    value="1"
                    checked={currentPayType === '1'}
                    onChange={() => this.onPayTypeChange('1')}
                  >
                    线下支付
                  </Radio>
                  <Radio
                    value="2"
                    checked={currentPayType === '2'}
                    onChange={() => this.onPayTypeChange('2')}
                  >
                    线上支付
                  </Radio>
                </View>
              </View>
            </View>
            <View className="card-tips">提示：线下支付支持到驿站或上门服务时刷老年卡</View>
            <View className="section-block">
              <AtList>
                <InputItem
                  name="remark"
                  title="留言"
                  value={submitForm.remark}
                  onChange={this.onRemarkChange}
                />
              </AtList>
            </View>
          </View>
        </Tabs>
        <View className="bottom-btn">
          <View className="bottom-left">
            <View className="select-title">待支付</View>
            <View className="select-time">￥{(skuInfo.price * count).toFixed(2)}</View>
          </View>
          <View className="bottom-right">
            <AtButton onClick={this.onSubmit}>提交订单</AtButton>
          </View>
        </View>
        <SelectUser
          show={visibleSelect}
          onClose={() => {
            this.setState({
              visibleSelect: false,
            });
          }}
          list={userList}
          onSelect={this.onSelectUser}
        />
        <SelectAddress
          show={visibleAddress}
          onClose={() => {
            this.setState({
              visibleAddress: false,
            });
          }}
          list={userList}
          onSelect={this.onSelectUser}
        />
        <TimeModal
          currentDate={getFirstDay()}
          currentTime={getAppointmentDate()}
          show={appointDateMoalShow}
          onChange={this.onAppointTimeChange}
          onClose={() => {
            this.setState({
              appointDateMoalShow: false,
            });
          }}
        />
      </View>
    );
  }
}
